#include "stdafx.h"
//-------------------------------------------------------------------------------------------------
//ArchiveProcApp.cpp - Defines the entry point for the console application            
//-------------------------------------------------------------------------------------------------
//FreeBSD License
//Copyright 2011 Will Stott All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are
//permitted provided that the following conditions are met:
//
//   1. Redistributions of source code must retain the above copyright notice, this list of
//      conditions and the following disclaimer.
//
//   2. Redistributions in binary form must reproduce the above copyright notice, this list
//      of conditions and the following disclaimer in the documentation and/or other materials
//      provided with the distribution.
//
//THIS SOFTWARE IS PROVIDED BY Will Stott ``AS IS'' AND ANY EXPRESS OR IMPLIED
//WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
//FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Will Stott OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
//ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
//ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//The views and conclusions contained in the software and documentation are those of the
//authors and should not be interpreted as representing official policies, either expressed
//or implied, of Will Stott.
//
//----Authors--------------------------------------------------------------------------------------
//created by: will.stott@ucl.ac.uk Feb 2011
//
//----Comments-------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------

#include <stdlib.h>
#include <iostream>
#include <vector>
#include <Objbase.h>
#include <fstream>
#include <string>

#include "APDatabase.h"
#include "ImageProcLib.h"
#include "ImageDataset.h"
#include "UraDb.h"
#include "SqlProc.h"
#include "FreeBSDLicence.h"

const int MAX_DBCONNECTIONLABEL=50;
const int MAX_FILENAME=128;

const TCHAR * const SqlStatementFilenameDefault = L"Sql-StaticImageReview-10800-test1.txt";
const TCHAR * const IdfFilenameDefault = L"StaticImageReview.idf";
const TCHAR * const DataDirDefault = L"C:\\Users\\Wills\\Documents\\Visual Studio 2010\\Projects\\OCUDS-Production\\DataSets\\StaticImageReview\\";


bool	ArgProc( int argc,  TCHAR**argv, TCHAR *DbConnectLabel, int DbConnectLabelLen, TCHAR *SqlStatementPathFilename, int SqlStatementPathFilenameLen, TCHAR *IdfPathFilename, int IdfPathFilenameLen,  TCHAR *DataDir, size_t DataDirLen );
void	ArgHelp( int argc,  TCHAR**argv);

int _tmain(int argc, TCHAR** argv)
{
	using std::wcout;
	using std::endl;
	using std::wstring;

	TCHAR DbConnectionLabel[MAX_DBCONNECTIONLABEL];
	TCHAR SqlStatementPathFilename[_MAX_PATH + MAX_FILENAME];
	TCHAR IdfPathFilename[_MAX_PATH + MAX_FILENAME];
	TCHAR DataDir[_MAX_PATH];

	wcout << L"ArchiveProcApp v1.0.0.4" << endl;

	wcout <<  AppLicenceText; 
	wcout <<  APDatabase::GetLibName() << " " << APDatabase::GetLibVersion() << endl;
	wcout <<  ImageProcLib::GetLibName() << " " << ImageProcLib::GetLibVersion() << endl;
	wcout <<  endl;

	if ( ::ArgProc( argc, argv, DbConnectionLabel, MAX_DBCONNECTIONLABEL, SqlStatementPathFilename, _MAX_PATH + MAX_FILENAME, IdfPathFilename, _MAX_PATH + MAX_FILENAME, DataDir, _MAX_PATH ) == false)
		::ArgHelp(argc, argv);
	else
	{
		CoInitializeEx(NULL, COINIT_MULTITHREADED);

		UraDb conn;
				

		if (conn.OpenDbSession(DbConnectionLabel) == false)
			wcout << L"open database session failed" << endl;
		else
		{
			wcout << L"open database session ok" << endl;

			ImageDataset idf(IdfPathFilename, "Image workflow engine v0.0 - image dataset file", "Doc");

			SqlProc sql;
			sql.OpenStatementsFile(SqlStatementPathFilename);

			for (std::vector<std::wstring *>::iterator statement = sql._Statements.begin(); statement != sql._Statements.end(); ++statement ) 
			{
				LPCOLESTR SqlQuery = (*statement)->c_str();   
			
				if ( ! conn.GetRecords(SqlQuery, 100))
				{
					wcout << L"conn.GetRecords failed, msg: "; 
					if (FAILED(conn.GetErrorCode()))
						wcout << conn.GetErrorMsg() << endl;
					else
						wcout << L"(no HRESULT message)" << endl;
					break;
				}
				else
				{
					if ( conn._Images.size() == 0 )
					{
						wcout << L"conn.GetRecords returned no records for:  " << SqlQuery;
						break;
					}

					ImageData *pImageData;
					for (std::vector<ImageData *>::iterator iter = conn._Images.begin(); iter != conn._Images.end(); ++iter ) 
					{
						pImageData = *iter;
						if (pImageData->GetErrorCode() != ImageData::NoError )
						{
							if (pImageData->GetErrorCode() == ImageData::DicomError )
								wcout << L"Dicom Error " << pImageData->GetDicomFile()->GetErrorMsg() << endl;
							else
								wcout << L"ImageData Error " << pImageData->GetErrorMsg() << endl;
						}
						else
						{
							wcout << L"file stored by " << pImageData->GetStoredBy() << endl;
							wcout << L"file record size " <<  pImageData->GetDicomFile()->GetDicomFileLength() << endl;
							wcout << L"DICOM Ref " << pImageData->GetDicomFile()->GetDicomRef() << endl;

							if ( pImageData->GetBitMap()->SaveAsFile(DataDir))
							{
								idf.AddImage(pImageData->GetDicomFile()->GetDicomRef());
								wcout << L"BMP file saved ok" << endl;
							}
							else
								wcout << L"BMP file save error" << endl;

							//if ( pImageData->GetDicomFile()->SaveAsFile(DataDir))
							//	wcout << L"DICOM file saved ok" << endl;
							//else
							//	wcout << L"DICOM file save error" << endl;

		//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		/*					wstring filenameNOK(DataDir);
							filenameNOK += pImageData->GetBitMap()->GetDicomRef();
							filenameNOK += L".bmp";

							wstring filenameOK(DataDir);
							filenameOK += L"testOK";
							filenameOK += L".bmp";

							wcout << L"difference = " << ImageData::CompareFiles(filenameOK.c_str(),filenameNOK.c_str() );*/
		//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

						}
						wcout << endl << endl;
					}
				}
			}
			idf.SaveFile(NULL); //IdfPathFilename);
			conn.CloseDbSession();
			wcout << L"close database session ok" << endl;
		}

		CoUninitialize();
	}

	wcout << endl << L"program ends" << endl;

	return 0;
}


bool	ArgProc( int argc,  TCHAR**argv, TCHAR *DbConnectLabel, int DbConnectLabelLen, TCHAR *SqlStatementPathFilename, int SqlStatementPathFilenameLen, TCHAR *IdfPathFilename, int IdfPathFilenameLen,  TCHAR *DataDir, size_t DataDirLen )
{
	using std::ifstream;
	using std::string;
	using std::basic_string;
	using std::wcout;
	using std::endl;

//#pragma warning(disable:4996)
	bool rc = false;

	wcout << L"Args=" << argc << endl;
	if ( argc > 0 )
		wcout << L"DbConnectionLabel (max " << MAX_DBCONNECTIONLABEL << L") = " << argv[1] << endl;
	if ( argc > 1 )
		wcout << L"SqlStatementPathFilename (max " << _MAX_PATH + MAX_FILENAME << L") = " << argv[2] << endl;
	if ( argc > 2 )
		wcout << L"IDFPathfilename (max " << _MAX_PATH + MAX_FILENAME << L") = "  << argv[3] << endl;
	if ( argc > 3 )
		wcout << L"DataDir (max " << _MAX_PATH << L") = " << argv[4] << endl;

	if (argc == 5 )
	{
		size_t DataDirCnt = 0;

		wcsncpy( DbConnectLabel, argv[1], DbConnectLabelLen);
		DbConnectLabel[DbConnectLabelLen-1] = '\0';

		wcsncpy( DataDir, argv[4], DataDirLen);
		DataDir[DataDirLen-1] = '\0';
		DataDirCnt = wcslen(DataDir);
		if ( DataDirCnt < DataDirLen )
		{
			DataDir[DataDirCnt] = '\\';
			DataDirCnt++;

			wcsncpy( SqlStatementPathFilename, DataDir, SqlStatementPathFilenameLen);
			wcsncpy( &SqlStatementPathFilename[DataDirCnt], argv[2], SqlStatementPathFilenameLen-DataDirCnt);
			SqlStatementPathFilename[SqlStatementPathFilenameLen-1] = '\0';

			wcsncpy( IdfPathFilename, DataDir, IdfPathFilenameLen);
			wcsncpy( &IdfPathFilename[DataDirCnt], argv[3], IdfPathFilenameLen-DataDirCnt);
			IdfPathFilename[IdfPathFilenameLen-1] = '\0';

			ifstream statementsFile;
			try
			{
				statementsFile.open (SqlStatementPathFilename, std::ios::in ); 
				if (statementsFile.is_open()) 
					rc = true;
				statementsFile.close();
			}
			catch(...)
			{
				rc = false;
			}
		}
	}
	return rc;

//#pragma warning(default:4996)
}

void ArgHelp(int argc,  TCHAR**argv )
{
	using std::wcout;
	using std::endl;

	wcout << endl << L"*** Error: invalid args ***" << 	endl << endl;
	wcout << L"There should be 4 arguments, found " << argc-1 << endl;

	if ( argc > 0 )
		wcout << L"argv[1] (DbConnectLabel) =" << argv[1] << endl;
	else
		wcout << L"argv[1] DbConnectLabel is missing, try " << DbConnectLabelDefault << endl;

	if ( argc > 1 )
		wcout << L"argv[2] (SqlStatement Filename) =" << argv[2] << endl;
	else
		wcout << L"argv[2] SqlStatement Filename is missing, try " << SqlStatementFilenameDefault << endl;

	if ( argc > 2 )
		wcout << L"argv[3] (IDF Filename) =" << argv[3] << endl;
	else
		wcout << L"argv[3] IDF Filename is missing, try " << IdfFilenameDefault << endl;

	if ( argc > 3 )
		wcout << L"argv[4] Data Directory =" << argv[4] << endl;
	else
		wcout << L"argv[4] Data Directory is missing, try " << DataDirDefault << endl;

	wcout << endl << L"Check SqlStatement file exists in Data Directory" << endl; 

	wcout << endl;
}

//-------------------------------------------------------------------------------------------------
//			E N D   O F   F I L E
//-------------------------------------------------------------------------------------------------
